package LeetCode_21;

import LeetCode_206.ListNode;

import java.util.List;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2022/10/22 23:51
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode head1 = list1;
        ListNode head2 = list2;
        //结果链表的头节点 和尾节点
        ListNode ansHead = new ListNode(); //工具节点
        ListNode ansLast = ansHead; //当前头尾公用一个节点
        while (head1!=null && head2 != null){
            if (head1.val <= head2.val){
                ListNode cur = head1;
                head1= head1.next;
                ansLast.next = cur;
                ansLast = cur;
            }else {
                ListNode cur = head2;
                head2 =head2.next;
                ansLast.next = cur;
                ansLast = cur;
            }
        }
        //head1==null || head2 == null
        if (head1!=null){
            ansLast.next = head1;
        }else {
            ansLast.next = head2;
        }

        return ansHead.next;
    }
    public ListNode mergeTwoLists1(ListNode list1, ListNode list2) {
        ListNode preHead = new ListNode(-1);
        ListNode prev = preHead;
        while ( list1!=null && list2 != null){
            if (list1.val <= list2.val){
                prev.next = list1;
                list1 = list1.next;
            }else {
                prev.next = list2;
                list2 = list2.next;
            }
            prev = prev.next;
        }
        prev.next = list1==null? list2 :list1;
        return preHead.next;
    }
    public ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
        if(list1 == null){
            return list2;
        }else if(list2 == null){
            return list1;
        }else if(list1.val > list2.val){
            list2.next = mergeTwoLists(list1,list2.next);
            return list2;
        }else {
            list1.next = mergeTwoLists(list1.next,list2);
            return list1;
        }
    }
}
